package com.bdqn.tour.servlet.Hzy;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.dao.impl.HzyTravelersDaoImpl;
import com.bdqn.tour.pojo.HzyTraveler_documents;
import com.bdqn.tour.pojo.HzyTravelers;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/updateTraveler")
public class UpdateTravelerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取基本信息
        String idStr = req.getParameter("id");
        int id = (idStr != null && !idStr.isEmpty()) ? Integer.parseInt(idStr) : 0;
        String chineseName = req.getParameter("chineseName");
        String surname = req.getParameter("surname");
        String givenName = req.getParameter("givenName");
        String gender = req.getParameter("gender");
        String nationality = req.getParameter("nationality");
        String phone = req.getParameter("phone");
        // 创建travelers对象
        HzyTravelers traveler = new HzyTravelers();
        traveler.setId(id);
        traveler.setChineseName(chineseName);
        traveler.setSurname(surname);
        traveler.setGivenName(givenName);
        traveler.setGender(gender);
        traveler.setNationality(nationality);
        traveler.setPhone(phone);
        // 获取证件信息
        String[] documentTypes = req.getParameterValues("documentType");
        String[] documentNumbers = req.getParameterValues("documentNumber");
        String[] expiryDates = req.getParameterValues("expiryDate");
        HzyTravelersDaoImpl travelersDao = new HzyTravelersDaoImpl();
        boolean success;
        if (id > 0) {
            // 更新旅客基本信息
            success = travelersDao.updateTraveler(traveler);
            if (success) {
                // 先删除旧的证件信息
                travelersDao.deleteAllDocuments(traveler.getId());
                // 添加新的证件信息
                if (documentTypes != null && documentNumbers != null) {
                    // 使用Set来防止重复的证件类型
                    Set<String> processedTypes = new HashSet<>();
                    List<HzyTraveler_documents> documents = new ArrayList<>();
                    for (int i = 0; i < documentTypes.length; i++) {
                        if (documentNumbers[i] != null && !documentNumbers[i].trim().isEmpty()) {
                            // 检查是否已处理过该类型的证件
                            if (!processedTypes.add(documentTypes[i])) {
                                continue; // 跳过重复的证件类型
                            }
                            HzyTraveler_documents doc = new HzyTraveler_documents();
                            doc.setTraveler_id(id);
                            doc.setDocument_type(documentTypes[i]);
                            doc.setDocument_number(documentNumbers[i]);
                            // 护照需要处理有效期
                            if ("护照".equals(documentTypes[i]) && expiryDates != null && i < expiryDates.length) {
                                doc.setExpiry_date(expiryDates[i]);
                            }

                            travelersDao.addTraveler_documents(doc);
                            documents.add(doc);

                        }
                    }
                    traveler.setDocuments(documents);
                }
                result.put("success", true);
                result.put("message", "更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新失败");
            }
        } else {
            // 新增旅客
            id = travelersDao.addTraveler(traveler);
            if (id > 0) {
                // 添加证件信息
                if (documentTypes != null && documentNumbers != null) {
                    Set<String> processedTypes = new HashSet<>();
                    List<HzyTraveler_documents> documents = new ArrayList<>();
                    for (int i = 0; i < documentTypes.length; i++) {
                        if (documentNumbers[i] != null && !documentNumbers[i].trim().isEmpty()) {
                            if (!processedTypes.add(documentTypes[i])) {
                                continue;
                            }
                            HzyTraveler_documents doc = new HzyTraveler_documents();
                            doc.setTraveler_id(id);
                            doc.setDocument_type(documentTypes[i]);
                            doc.setDocument_number(documentNumbers[i]);
                            if ("护照".equals(documentTypes[i]) && expiryDates != null && i < expiryDates.length) {
                                doc.setExpiry_date(expiryDates[i]);
                            }

                            travelersDao.addTraveler_documents(doc);
                            documents.add(doc);

                        }
                    }
                    traveler.setDocuments(documents);
                }
                result.put("success", true);
                result.put("message", "添加成功");
                result.put("id", id);
            } else {
                result.put("success", false);
                result.put("message", "添加失败");
            }
        }

        String json = JSON.toJSONString(result);
        out.print(json);
        out.close();
    }

}
